<template>
  <basic-container>
    <!--    筛选条件-->
    <cs-filter-query ref="csFilterQueryRef" :options="filterQueryOptions" @change="handleChangeFilter">
    </cs-filter-query>

    <!--    表格列-->
    <div class="curd-table">
      <div class="tab-header clearfix" style="margin:10px 0 20px 30px ">
        <div class="tab-header-left">
          <el-button size="mini" type="primary" @click="addAccount">新增</el-button>
          <el-button size="mini" type="warning" @click="selectionSubmitAudit">提交审核</el-button>
          <el-button size="mini" type="danger"  @click="deleteAccounts" :disabled="this.multipleSelection.length == 0">删除</el-button>
        </div>
        <div class="tab-header-right" style="margin-right: 30px">
          <el-tooltip class="item" effect="dark" content="刷新" placement="top">
            <el-button icon="el-icon-refresh" size="mini" circle @click="refreshAccount"></el-button>
          </el-tooltip>
        </div>
      </div>

      <div class="table-body">
        <el-table v-loading="loading"
                  :data="accountList"
                  border
                  overflower
                  :header-cell-style="iHeaderCellStyle"
                  style="width: 100%"
                  @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="40"></el-table-column>
          <el-table-column label="序号" type="index" width="50" align="center"></el-table-column>
          <el-table-column prop="customerName" label="客户简称" width="180"
                           :show-overflow-tooltip='true'></el-table-column>
          <el-table-column prop="entityName" label="主体名称" width="180"
                           :show-overflow-tooltip='true'></el-table-column>
          <el-table-column prop="productName" label="产品名称" :show-overflow-tooltip='true'></el-table-column>
          <el-table-column prop="status" label="开户状态" width="100">
            <template v-slot="{row}">
              {{ findStatus(row.status) }}
            </template>
          </el-table-column>
          <el-table-column prop="platform" label="媒体" :show-overflow-tooltip='true'></el-table-column>
          <el-table-column prop="team" label="团队" :show-overflow-tooltip='true'>
            <template v-slot="{row}">
              {{ findDept(row.team) }}
            </template>
          </el-table-column>
          <el-table-column prop="rejectReason" label="拒绝原因" width="100" :show-overflow-tooltip='true'>
          </el-table-column>
          <!--          <el-table-column prop="timezone" label="账户时区" width="150" :show-overflow-tooltip='true'>-->
          <!--            <template v-slot="{row}">-->
          <!--              {{ findTimezone(row.timezone) }}-->
          <!--            </template>-->
          <!--          </el-table-column>-->
          <!--          <el-table-column prop="registeredArea" label="投放地区" width="100"-->
          <!--                           :show-overflow-tooltip='true'></el-table-column>-->
          <!--          <el-table-column prop="number" label="开户数量" width="80"></el-table-column>-->
          <!--          <el-table-column prop="licenseNo" label="营业执照编号" width="120" :show-overflow-tooltip='true'>-->
          <!--          </el-table-column>-->
          <el-table-column prop="createTime" label="创建时间" :show-overflow-tooltip='true'></el-table-column>
          <el-table-column prop="createUser" label="创建人" width="100" :formatter="formatterUserName">
          </el-table-column>
          <el-table-column prop="auditTime" label="审核完成时间" :show-overflow-tooltip='true'></el-table-column>
          <el-table-column label="操作" width="120" align="center" fixed="right">
            <template v-slot="{row}">
              <el-tooltip content="查看" placement="top">
                <el-button size="small" icon="el-icon-view" type="text" @click="showAccountOpen(row)"></el-button>
              </el-tooltip>
              <el-tooltip content="编辑" placement="top">
                <el-button size="small" v-if="" icon="el-icon-edit" type="text" :disabled="!(row.status==0 || row.status==2)"
                           @click="editOrCopyReportNew(row, '编辑')"></el-button>
              </el-tooltip>
              <el-tooltip content="复制" placement="top">
                <el-button size="small" icon="el-icon-document-copy" type="text"
                           @click="editOrCopyReportNew(row, '复制')"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button size="small" icon="el-icon-delete" type="text" :disabled="row.status!==0"
                           @click="deleteAccount(row.id)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="bottom-page clearfix">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.current"
          :page-sizes="[10, 20, 30, 40, 50, 100]"
          :page-size="page.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>

    <!--    新增，查看弹窗-->
    <el-drawer
      v-loading="loading"
      :title="drawerTitle"
      size="830px"
      :visible.sync="drawerSwitch"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :append-to-body="true"
      :wrapperClosable="false"
      @close="closeDrawer"
      class="addDrawer"
    >
      <el-divider></el-divider>
      <div style="margin-left: 20px;margin-bottom: 20px" v-show="drawerTitle==='查看'">开户信息</div>
      <cs-drawer-container>
        <el-form :model="accountForm" ref="accountForm" class="add-form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="开户媒体:">
                <el-select size="mini" v-model="accountForm.platform" filterable
                           @change="mediaChange"
                           :disabled="drawerTitle==='查看'">
                  <el-option v-for="(item,index) in mediaList" :key="index" :value="item.value" :label="item.label">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <div>
            <!--五家媒体公关参数字段-->
            <el-row>
              <el-col :span="12" >
                <el-form-item label="公司简称:" prop="customerName">
                  <el-select size="mini" v-model="accountForm.customerName" clearable filterable
                             @change="changeFullName(accountForm.customerName)" @clear="clearCustomerFullName"
                             :disabled="drawerTitle==='查看'">
                    <el-option v-for="(item,index) in customerList" :key="index" :value="item.label" :label="item.label">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
                <el-col :span="12" v-if="accountForm.platform != 'google'">
                  <el-form-item label="主体名称:" prop="entityName">
                    <el-select size="mini" v-model="accountForm.entityName" clearable filterable
                               style="width: calc(100% - 117px)"
                               :disabled="drawerTitle==='查看'" @change="handleChangeEntity"
                               @clear="clearEntityName"
                               placeholder="请选择主体或者输入新主体名称">
                      <el-option v-for="(item,index) in accountEntityList"
                                 :key="index" :value="item.entityName" :label="item.entityName">
                      </el-option>
                    </el-select>
                    <el-button size="mini" icon="el-icon-edit" @click="editEntity"
                               :disabled="!accountEntityList.some(item=>item.entityName ===accountForm.entityName)  || drawerTitle==='查看'"></el-button>
                    <el-button size="mini" icon="el-icon-plus" @click="addEntity"
                               style="margin-left: unset"
                               :disabled="drawerTitle==='查看' || accountForm.platform == 'google' ">新增
                    </el-button>
                  </el-form-item>
                </el-col>
              <el-col :span="24">
                <el-form-item label="推广链接:" prop="appLink" clearable>
                  <el-input v-model.trim="accountForm.appLink" size="mini" placeholder="请输入"
                            :disabled="drawerTitle==='查看'" @blur="changeAccountName(accountForm.appLink)"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <!--产品链接是否有地域访问限制 + fbAppId-->
              <div v-if="accountForm.platform == 'facebook'">
                <el-col :span="12">
                  <el-form-item label="推广链接地域限制:" prop="geoLimit" label-width="140px">
                    <el-radio-group v-model="accountForm.geoLimit"
                                    :disabled="drawerTitle==='查看'">
                      <el-radio :label="0">否</el-radio>
                      <el-radio :label="1">是</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="App ID:"  >
                    <el-input
                      placeholder="请输入Facebook App ID"
                      v-model.trim="accountForm.fbAppId"
                      :disabled="drawerTitle==='查看'"
                      size="mini"
                      clearable>
                    </el-input>
                  </el-form-item>
                </el-col>
              </div>
              <!--账户时区-->
              <div>
                <el-col :span="12" v-if="accountForm.platform != 'kwai'">
                  <el-form-item label="账户时区:" prop="timezone">
                    <el-select size="mini" v-model="accountForm.timezone" clearable filterable
                               :disabled="drawerTitle==='查看'">
                      <el-option v-for="(item,index) in timeZoneList" :key="index" :value="item.dictKey" :label="item.dictValue">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </div>
              <!--开户类型-->
              <div  v-if="['facebook','google'].includes(accountForm.platform)">
                <el-col :span="12">
                  <el-form-item label="开户类型:" prop="accountType">
                    <el-select v-model="accountForm.accountType"   :disabled="drawerTitle==='查看'" size="mini" @change="accountTypeChange">
                      <el-option label="国内代理" value="国内代理"></el-option>
                      <el-option label="海外代理-阿根廷" value="海外代理-阿根廷"></el-option>
                      <el-option label="海外代理-尼日利亚" value="海外代理-尼日利亚"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </div>
              <!--主体注册地+开户状态-->
              <div v-if="accountForm.platform=='tiktok'">
                <el-col :span="12">
                  <el-form-item label="主体注册地" prop="registeredArea">
                    <el-select size="mini" v-model="accountForm.registeredArea" clearable filterable
                               :disabled="drawerTitle==='查看'" >
                      <el-option v-for="(item,index) in nationList" :key="index" :value="item.dictKey"
                                 :label="item.dictValue">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </div>
              <div v-if="['kwai','bigo'].includes(accountForm.platform)">
                <el-col :span="12">
                  <el-form-item label="投放地区" prop="multipleRegisteredArea">
                    <el-select size="mini" v-model="accountForm.multipleRegisteredArea" clearable filterable
                               :disabled="drawerTitle==='查看'" multiple>
                      <el-option v-for="(item,index) in KBnationList" :key="index" :value="item.dictKey"
                                 :label="item.dictValue">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </div>
              <el-col :span="12" v-if="this.drawerTitle==='查看'">
                <el-form-item label="开户状态:" >
                  <span class="status">{{ findStatus(accountForm.status) }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="账户命名:" prop="baseName">
                  <el-input v-model.trim="accountForm.baseName" size="mini" placeholder="格式：ads4each-产品名称-公司简称"
                            :disabled="drawerTitle==='查看'"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="开户数量:" prop="number">
                  <el-input @blur="defaultNumber(accountForm.number)" type="number"
                            v-model.trim="accountForm.number" size="mini"
                            placeholder="请输入"
                            :disabled="drawerTitle==='查看'"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="币种:" prop="currency">
                  <el-select size="mini" v-model="accountForm.currency" clearable filterable
                             :disabled="drawerTitle==='查看'" @change="currencyChange">
                    <el-option v-for="(item,index) in currencyList" :key="index" :value="item.value" :label="item.label">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12" style="height: 62.8px" >
                <el-form-item label="充值金额:" prop="prepareRechargeAmount" :required="true">
                  <div style="display:inline-flex ">
                    <el-input-number v-model.trim="accountForm.prepareRechargeAmount" controls-position="left" :min="0" :precision="2" :step="0.01" size="small" :disabled="drawerTitle==='查看'">
                      <i slot="prefix" style="font-style:normal;margin-right: 10px;">cm</i>
                    </el-input-number>
                    <span class="currencyName">{{accountForm.currency}}</span>
                    <!--                   <template slot="append">{{accountForm.currency}}</template>-->
                  </div>
                </el-form-item>
              </el-col>
              <!--执照编号-->
              <div v-if="['tiktok','facebook','kwai'].includes(accountForm.platform)">
                <el-col :span="12" style="height: 62.8px">
                  <el-form-item label="执照编号:" prop="licenseNo">
                    <el-input v-model.trim="accountForm.licenseNo" size="mini" placeholder="请输入" clearable
                              :disabled="drawerTitle==='查看'"></el-input>
                  </el-form-item>
                </el-col>
              </div>
              <!--行业-->
              <div v-if="['tiktok','bigo'].includes(accountForm.platform)">
                <el-col :span="12"  >
                  <el-form-item label="账户行业:" prop="industry" >
                    <el-select size="mini" v-model="accountForm.industry" clearable filterable
                               :disabled="drawerTitle==='查看'">
                      <el-option v-for="(item,index) in industryList" :key="index" :value="item.dictKey"
                                 :label="item.dictValue">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </div>
              <div v-if="accountForm.platform=='kwai'" class="cascader">
                <el-col :span="12"  style="height: 62.8px">
                  <el-form-item label="账户行业:" prop="industry" >
                    <el-cascader
                      v-model="accountForm.industry"
                      :disabled="drawerTitle==='查看'"
                      style="width: 100%"
                      size="mini"
                      popper-class="popper"
                      placeholder="请选择账户行业"
                      :options="kwaiIndustryList"
                      :props="{value:'dictKey',label:'dictValue',checkStrictly: true,expandTrigger:'hover'}"
                      filterable></el-cascader>
                  </el-form-item>
                </el-col>
              </div>
              <!--备注-->
              <div v-if="['facebook','google'].includes(accountForm.platform)">
                <el-col :span="24">
                  <el-form-item label="备注:">
                    <el-input type="textarea" v-model.trim="accountForm.remarks"  :disabled="drawerTitle==='查看'"></el-input>
                  </el-form-item>
                </el-col>
              </div>
              <!--营业执照-->
              <div v-if="accountForm.platform != 'google'">
                <el-col :span="24" v-if="drawerTitle!='查看'">
                  <el-form-item label="营业执照:" prop="licenseImage">
                    <file-uploader ref="fileUploader" :limit=1
                                   uplodParame='license'
                                   :file-list="getLicense"
                                   accept=".png,.jpg,.jpeg"
                                   @uploadFinished="uploadFinished"
                                   @fileDeleted="fileDeleted">
                      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
                    </file-uploader>
                  </el-form-item>
                </el-col>
                <el-col :span="13" v-else>
                  <el-form-item label="营业执照:" prop="licenseImage" disabled>
                    <div class="rightullidiv">
                      <img :src="accountForm.licenseImage" class="rightulliimg" />
                      <i class="el-icon-download" style="left: 25%;" @click="licenseImageDownload(accountForm.licenseImage)"></i>
                      <i class="el-icon-zoom-in" style="right: 25%;" @click="enlargeImage(accountForm.licenseImage)"></i>
                    </div>
                  </el-form-item>
                </el-col>
              </div>
              <!--其它附件-->
              <div v-if="accountForm.platform == 'bigo'">
                <el-col :span="24" v-if="drawerTitle!='查看'">
                  <el-form-item label="附件:" prop="annex">
                    <file-uploader ref="fileUploaders" :limit=10
                                   uplodParame='annex'
                                   :file-list="getAnnex"
                                   accept=".png,.jpg,.jpeg,.pdf"
                                   @uploadFinished="uploadFinished"
                                   @fileDeleted="fileDeleted">
                      <div slot="tip" class="el-upload__tip">可以上传多个文件,jpg/jpeg/png/pdf</div>
                    </file-uploader>
                  </el-form-item>
                </el-col>
                <el-col :span="24" v-else>
                  <el-form-item label="附件:" prop="annex" >
                    <div class="annexDemo" v-show="this.accountForm.annexList.length != 0">
                      <div class="rightullidiv"  v-for="(item, index) in this.accountForm.annexList">
                        <img   :src="item"  class="rightulliimg"/>
                        <i class="el-icon-download" style="left: 25%;" @click="licenseImageDownload(item)"></i>
                        <i class="el-icon-zoom-in" style="right: 25%;" @click="enlargeImage(item)"></i>
                      </div>
                    </div>
                  </el-form-item>
                </el-col>
              </div>
              <!--含网址的网站截图-->
              <div v-if="accountForm.platform == 'facebook' && accountForm.geoLimit == 1">
                <el-col :span="12" v-if="drawerTitle!='查看'">
                  <el-form-item label="含网址的网站截图:" prop="websiteScreenshot" label-width="140px">
                    <file-uploader ref="fileUploaderWeb" :limit=1
                                   uplodParame='website'
                                   :file-list="getWebsiteImage"
                                   accept=".png,.jpg,.jpeg"
                                   @uploadFinished="uploadFinished"
                                   @fileDeleted="fileDeleted">
                      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
                    </file-uploader>
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-else>
                  <el-form-item label="含网址的网站截图:" prop="websiteScreenshot" disabled  label-width="140px">
                    <div class="rightullidiv" v-show="this.accountForm.geoLimit == 1"  >
                      <img :src="accountForm.websiteScreenshot" class="rightulliimg" />
                      <i class="el-icon-download" style="left: 25%;" @click="licenseImageDownload(accountForm.websiteScreenshot)"></i>
                      <i class="el-icon-zoom-in" style="right: 25%;" @click="enlargeImage(accountForm.websiteScreenshot)"></i>
                    </div>
                  </el-form-item>
                </el-col>
              </div>
            </el-row>
          </div>

        </el-form>

        <div style="margin-left: 20px;margin-top: 20px;margin-bottom:30px" v-show="drawerTitle==='查看'">账户信息</div>
        <div style="margin-left:50px " v-show="drawerTitle==='查看'">
          <el-table :data="relativeAccounts" center style="width: 100%;" @selection-change="selectionChange">
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>
            <el-table-column
              prop="account_name"
              label="账户名称"
              width="300">
            </el-table-column>
            <el-table-column
              prop="account_id"
              label="账户ID"
              width="300">
              <template v-slot="{row}">
                {{ row.account_id == -1 ? '' : row.account_id }}
              </template>
            </el-table-column>
            <el-table-column
              prop="status"
              label="状态"
              width="300">
              <template v-slot="{row}">
                {{ findStatus(row.status) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div style="margin-left: 20px;margin-top: 20px;margin-bottom:30px" v-show="drawerTitle==='查看'">节点记录</div>
        <div style="margin-left:50px " v-show="drawerTitle==='查看'">
          <el-table :data="recordNode" center style="width: 100%;">
            <el-table-column
              prop="status"
              label="状态"
              width="300">
              <template v-slot="{row}">
                {{ findStatus(row.status) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="updateTime"
              label="操作时间"
              width="300">
            </el-table-column>
            <el-table-column
              prop="operatorName"
              label="操作人"
              width="300">
            </el-table-column>
          </el-table>
        </div>

        <template v-slot:bottom>
          <el-button type="warning" :loading="auditLoading" size="mini" @click="saveAndAudit" :disabled="btnLock"
                     v-show="drawerTitle==='新增开户申请' || drawerTitle==='复制'">
            提交审核
          </el-button>
          <el-button type="warning" size="mini" @click="updateAndAudit" :disabled="btnLock"
                     v-show="drawerTitle==='编辑'">
            提交审核
          </el-button>
          <el-button type="primary" :loading="saveLoading" size="mini" @click="addSave" :disabled="btnLock"
                     v-show="drawerTitle==='新增开户申请' || drawerTitle==='复制' ">保存
          </el-button>
          <el-button type="primary" size="mini" @click="editAccount" :disabled="btnLock"
                     v-show="drawerTitle==='编辑' && editSaveStatus">保存
          </el-button>
          <el-button type="primary" size="mini" @click="cancel">取消</el-button>
        </template>
      </cs-drawer-container>
    </el-drawer>

    <!--    新版弹窗-->
    <el-drawer
      title="请完善关联信息"
      v-loading="relatesSaveLoading"
      :visible.sync="relatesInformation"
      :before-close="handleCloseRelates"
      @open="oppenRelatesInformation"
      @close="closeRelatesInformation"
      size="55%"
      :wrapperClosable="false"
      append-to-body>
      <el-steps :active="active" process-status="finish" finish-status="success" simple style="margin-top: 20px">
        <el-step title="APP信息"></el-step>
        <el-step title="账户信息"></el-step>
      </el-steps>
      <el-divider></el-divider>
      <!--      app信息-->
      <div v-if="active===0">
        <el-form ref="appForm" :model="dialogForm" :rules="appRules" label-width="80px">
          <el-row>
            <el-col :span="18">
              <el-form-item label="客户:" prop="customerId" label-width="100px" disabled>
                <el-select size="mini" v-model="dialogForm.customerId" disabled>
                  <el-option v-for="(item,index) in customerList" :key="index" :value="item.value" :label="item.label">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="商店URL:" style="width: 98%" prop="appUrl" label-width="110px">
                <el-input id="id-business-appmanager-dialogForm-appUrl"
                          size="mini"
                          v-model.trim="dialogForm.appUrl"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item label="产品名称:" prop="name" label-width="110px">
                <el-input id="id-business-appmanager-dialogForm-name" size="mini"
                          v-model.trim="dialogForm.name"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="包名:" label-width="110px">
                <el-input size="mini" id="id-business-appmanager-dialogForm-appPackageId"
                          v-model.trim="dialogForm.appPackageId"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="11">
              <el-form-item label="类型:" label-width="110px">
                <el-input id="id-business-appmanager-dialogForm-category" size="mini"
                          v-model.trim="dialogForm.category"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="操作系统:" prop="os" label-width="110px">
                <el-select v-model="dialogForm.os" size="mini" placeholder="请选择">
                  <el-option
                    v-for="item in osList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="dialogForm.os===1||dialogForm.os===2">
            <el-col :span="12">
              <div class="avatars">
                <el-form-item label="上传图标:" label-width="110px">
                  <el-upload
                    class="avatar-uploader"
                    action="#"
                    :show-file-list="false"
                    :http-request="uploadQiniuCloud"
                    :before-upload="beforeAvatarUpload"
                    list-type="picture">
                    <img v-if="imageUrl" :src="imageUrl" width="120" height="120">
                    <i v-else class="el-icon-upload2"></i>
                  </el-upload>
                </el-form-item>
              </div>
            </el-col>
          </el-row>

          <!--          <div style="display: flex;justify-content:space-between;margin-right: 50px">-->
          <!--            &lt;!&ndash;          <el-button v-if="title!=='详情' && !dialogForm.isWebsite && !saveAppDiaable" type="success" :loading="urlLoading" @click="urlConfim">校验</el-button>&ndash;&gt;-->
          <!--            <el-button id="id-business-appmanager-dialogForm-handleClose" size="mini" @click="handleClose">取 消</el-button>-->
          <!--            <el-button id="id-business-appmanager-saveApp"-->
          <!--                       type="primary" size="mini" icon="el-icon-circle-plus-outline"-->
          <!--                       :loading="addLoading"-->
          <!--                       @click="next">下一步-->
          <!--            </el-button>-->

          <!--          </div>-->
        </el-form>
      </div>
      <!--      账户信息-->
      <div v-if="active===1" style="margin-top: 30px">
        <el-form ref="accountMsgForm" :model="offerForm" :rules="offerRules" class="demo-form-inline">
          <el-row :gutter="20">
            <el-col :span="11">
              <el-form-item label="订单名称" label-width="100px">
                <el-select v-model="offerForm.offerId" placeholder="请选择订单" @change="accountChangeOffer" filterable
                           clearable>
                  <el-option v-for="item in offerList"
                             :key="item.id"
                             :label="item.name"
                             :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-button type="primary" @click="addOfferVisible = true"><i class="el-icon-plus"></i>新增订单</el-button>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="11">
              <el-form-item label="账户所有人" label-width="100px">
                <el-select v-model="offerForm.user" placeholder="请选择" filterable clearable>
                  <el-option
                    v-for="item in allUserList"
                    :key="item.id"
                    :label="item.realName"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="账户运营人" label-width="100px">
                <el-select v-model="offerForm.operator" placeholder="请选择" filterable clearable>
                  <el-option
                    v-for="item in allUserList"
                    :key="item.id"
                    :label="item.realName"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div style="display: flex;justify-content:center">
        <el-button size="mini" @click="relatesInformation=false">取 消</el-button>
        <el-button v-if="active===1" :disabled="successAndNotExists" type="primary" size="mini" @click="prev">上一步
        </el-button>
        <el-button v-if="active===0" type="primary" size="mini" @click="next">下一步</el-button>
        <el-button v-if="active===1" type="primary" size="mini" :disabled="relatesSaveLoading" @click="saveRelateMsg">
          保存
        </el-button>
      </div>
    </el-drawer>

    <!--    新增订单弹窗-->
    <el-dialog
      title="新增订单"
      :visible.sync="addOfferVisible"
      append-to-body
      @open="openAddOffer"
      @close="closeAddOffer"
      width="43%">
      <el-form ref="addOfferForm" :model="addOfferForm" :rules="addOfferRules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="订单名称:" prop="offerName" label-width="100px">
              <el-input id="id-business-appmanager-dialogForm-appUrl"
                        size="mini"
                        v-model.trim="addOfferForm.offerName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="产品名称:" prop="productName">
              <el-input id="id-business-appmanager-dialogForm-name" size="mini"
                        v-model.trim="addOfferForm.productName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="客户:">
              <el-select size="mini" v-model="addOfferForm.customer" disabled>
                <el-option v-for="(item,index) in customerList" :key="index" :value="item.value" :label="item.label">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="广告组审核素材:" label-width="150px">
              <el-radio-group v-model="addOfferForm.adAuditCreative">
                <el-radio :label=0>是</el-radio>
                <el-radio :label=1>否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="团队" prop="studio">
              <el-select size="mini" v-model="addOfferForm.studio" @change="teamChange">
                <el-option
                  v-for="(item,index) in deptList"
                  :key="index"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="投放地区">
              <el-select size="mini" v-model="addOfferForm.nation" multiple>
                <el-option
                  v-for="item in orderNationList"
                  :key="item.geoKey"
                  :label="item.cnName +'-'+ item.geoKey + '-' + item.geoName"
                  :value="item.geoKey">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item label="优化师">
              <el-select size="mini" v-model="addOfferForm.optimized">
                <el-option
                  v-if="item.deptId.includes(addOfferForm.studio)"
                  v-for="item in optimizedList"
                  :key="item.id"
                  :label="item.realName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="设计师">
              <el-select size="mini" v-model="addOfferForm.designer">
                <el-option
                  v-if="item.deptId.includes(addOfferForm.studio)"
                  v-for="item in designerList"
                  :key="item.id"
                  :label="item.realName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
              <el-button @click="addOfferVisible = false">取 消</el-button>
              <el-button type="primary" @click="addOfferSave">保 存</el-button>
            </span>
    </el-dialog>
    <el-dialog
      :visible.sync="addEntityNameVisible"
      :append-to-body="true"
      width="30%">
      <el-form ref="addEntityNameForm" :model="addEntityNameForm" label-width="100px">
        <el-form-item label="主体新名称" prop="name" :required="true" :rules="entityNameRule">
          <el-input v-model.trim="addEntityNameForm.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="addEntityNameVisible = false">取 消</el-button>
          <el-button type="primary" @click="addEntityName">确 定</el-button>
        </span>
    </el-dialog>
    <!--    图片预览弹框-->
    <el-dialog title="图片预览" width="30%" append-to-body :visible.sync="imgDialog">
      <img width="100%" :src="previewUrl" alt/>
    </el-dialog>
  </basic-container>
</template>

<script>
import CsDrawerContainer from "@/components/CsDrawerContainer/CsDrawerContainer";
import FileSaver from "file-saver"
import {getCreateUser} from "@/api/system/operationLog";
import CsFilterQuery from '@/components/CsFilterQuery/CsFilterQuery'
import uploadObs from "@/components/beetles-upload/upload_obs";


import {
  getAccountList,
  save,
  getTimeZone,
  getIndustry,
  updateAudit,
  submitAudit,
  getProductName,
  getAppInfo,
  getRecordNodeList,
  saveAndAudit, removeAccountByIds, getAccountEntityList, updateAndAudit, updateEntityName,
  checkLicenseNoExist, getOfferDetailById
} from "@/api/accountOrTransfer/account"

import creativeUploadProdObs from "@/components/beetles-upload/creative_upload_prod_obs";
import {getCustomer} from "@/api/dataReport/cost-report-new";
import {getGeoList} from "@/api/system/dict";
import _ from "lodash";
import {deepClone} from "@/util/util";
import creativeUpload from "../../components/beetles-upload/creative_upload";
import * as qiniuTools from "../../util/qinnu_upload";
import FileUploader from "../../components/beetles-upload/file_uploader";
import {addApp, verifyProductUrl} from "@/api/business/appManager";
import {add, getOfferList} from "@/api/business/offer";
import {getAllUser} from "@/api/user";
import {getOptimizer, getDesignerSelect} from "@/api/offer/creative";
import {batchAddAccounts} from "@/api/business/account";
import {
  getBigoGeoList,
  getBigoIndustryList,
  getKwwaiIndustryList,
  getKwaiGeoList,
  getTiktokGeoList,
  getTiktokIndustry,
  getDeptList,
  getWorkrooms
} from "../../api/accountOrTransfer/account";
export default {
  name: "account",
  components: {
    FileUploader,
    CsDrawerContainer,
    CsFilterQuery,
    uploadObs,
    creativeUploadProdObs,
    creativeUpload
  },
  data() {
    // var checkAge = (rule, value, callback) => {
    //   if (!value) {
    //     return callback(new Error('年龄不能为空'));
    //   }
    //   setTimeout(() => {
    //     if (!Number.isInteger(value)) {
    //       callback(new Error('请输入数字值'));
    //     } else {
    //       if (value < 18) {
    //         callback(new Error('必须年满18岁'));
    //       } else {
    //         callback();
    //       }
    //     }
    //   }, 1000);
    // }
    const validateEntityName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入主体新名称'));
      } else {
        if (this.isEditEntity) {
          callback();
        } else {
          if (this.accountEntityList.some(item => item.entityName === value)) {
            callback(new Error('已经存在主体名称'));
          } else {
            callback();
          }
        }
      }

    }
    return {
      //预览弹框
      imgDialog:false,
      //图片预览路径
      previewUrl:'',
      reUploadCreate: true,
      imageUploadCreate: true,
      imageUploadIdCreate: false,
      loading: true,
      dialogVisible: false,
      dialogImageUrl: '',
      dialogType: '',
      editSaveStatus: true,
      addOrSubmit: null,
      imageUrl: '',
      pullproductName: '',
      appInfo: null,
      testData: [
        {
          companyName: '',
          country: 'china',
          pruductName: '',
          count: 10,
          listNumber: '125346546',
          status: '活跃',
          time: 'time',
          create: '今天',
          creater: '我啊',
        }],
      accountList: [],
      selectList: [],
      customerList: [],
      timeZoneList: [],
      nationList: [],
      KBnationList:[],
      //订单投放地区
      orderNationList: [],
      ttNationList: [],
      bigoNationList: [],
      kwaiNationList: [],
      industryList: [],
      ttIndustryList: [],
      bigoIndustryList: [],
      kwaiIndustryList: [],
      deptList: [],
      // 币种列表
      currencyList: [
        {
          value:'USD',
          label:'USD'
        }
      ],
      osList: [
        {value: 1, label: 'Android'},
        {value: 2, label: 'ios'},
        {value: 3, label: 'website'}
      ],
      appRules: {
        appUrl: {required: true, message: '请输入商品URL', trigger: 'blur'},
        name: {required: true, message: '请输入产品名称', trigger: 'blur'},
        os: {required: true, message: '请选择操作系统', trigger: 'change'}
      },
      offerRules: {
        offerId: {required: true, message: '请选择订单', trigger: 'change'},
        user: {required: true, message: '请选择账户所有人', trigger: 'change'},
        operator: {required: true, message: '请选择账户运营人', trigger: 'change'},
      },
      addOfferRules: {
        offerName: {required: true, message: '请输入订单名称', trigger: 'blur'},
        productName: {required: true, message: '请输入产品名称', trigger: 'blur'},
        studio:{required: true, message: '请选择团队', trigger: 'change'}
      },
      recordNode: [],

      relativeAccounts: [],
      relativeAccountsId: [],
      detailAccountList: [],
      tagsLength: '5',
      statusList: [
        {value: 0, label: '草稿'},
        {value: 1, label: '代理预审中'},
        {value: 2, label: '代理拒绝'},
        {value: 3, label: '媒体审核中'},
        {value: 4, label: '媒体通过'},
        {value: 5, label: '媒体拒绝'},
        {value: 6, label: '部分通过'},
      ],
      rules: {
        customerName: [
          {required: true, message: '请选择公司简称', trigger: 'blur'},
        ],
        timezone: [
          {required: true, message: '请选择账户时区', trigger: 'blur'}
        ],
        appLink: [
          {required: true, message: '请输入推广链接', trigger: 'blur'}
        ],
        baseName: [
          {required: true, message: '请填写账户命名', trigger: 'blur'}
        ],
        number: [
          {required: true, message: '请填写开户数量', trigger: 'blur'}
        ],
        licenseNo: [
          {required: true, message: '请输入营业执照编号', trigger: 'blur'}
        ],
        industry: [
          {required: true, message: '请选择广告账户行业', trigger: 'blur'}
        ],
        entityName: [
          {required: true, message: "请选择主体名称", trigger: "blur"}
        ],
        currency: [
          {required: true, message: "请选择币种", trigger: "blur"}
        ],
        // fbAppId:[
        //   {required: true, message: '请填写 APP_ID', trigger: 'blur'},
        //   { pattern: /^.{3,20}$/, message: '长度最大为300字符', trigger: 'blur' }
        // ],
        geoLimit: [
          {required: true, message: "请选择是否有地域限制", trigger: "blur"}
        ],
        accountType: [
          {required: true, message: "请选择开户类型", trigger: "blur"}
        ],
        registeredArea: [
          {required: true, message: "请选择注册地", trigger: "blur"}
        ],
        multipleRegisteredArea: [
          {required: true, message: "请选择投放地区", trigger: "blur",type: 'array',}
        ],
        licenseImage: [{required: true, message: "请上传营业执照", trigger: "blur"}],
        websiteScreenshot:[{required: true, message: "请上传网站截图", trigger: "blur"}]
      },
      dialogForm: { //form表单值
        customerId: null,
        isWebsite: false,
        appUrl: null,
        impressionMonitorUrl: null,
        clickMonitorUrl: null,
        name: null,
        os: '',
        // logoUrl: null,
        appPackageId: null,
        category: null,
        imageUrl: null
      },
      addLoading: false,
      addAndCopySubmitAudit: false,
      // loading: true,
      query: '',
      dialogFormVisible: false,
      drawTestnumber: false,
      page: {
        current: 1,
        size: 10,
      },
      total: 0,
      drawerSwitch: false,
      // 弹窗表头
      drawerTitle: '',
      // 订单列表
      offerList: [],
      allUserList: [],
      createUserList: [],
      accountEntityList: [],
      copyProductName: '',
      relatesSaveLoading: false,
      //多选
      // multipleRegisteredArea:[],
      // 新增添加表单
      accountForm: {
        multipleRegisteredArea:[],
        id: null,
        customerId: 1,
        customerName: '',
        entityId: null,
        entityName: '',
        customerFullName: '',
        timezone: '',
        baseName: 'ads4each-[产品名称]-[公司简称]',
        number: 1,
        licenseNo: '',
        // money:'',
        appLink: '',
        licenseImage: '',

        industry: '',
        prepareRechargeAmount: 0,
        //开户媒体
        platform:'tiktok',
        //推广链接是否地域访问限制
        geoLimit:0,
        //fbAppId
        fbAppId:'',
        // 投放地区
        registeredArea:'',
        // 开户类型
        accountType: '国内代理',
        //币种
        currency:'USD',
        //网站截图
        websiteScreenshot:'',
        //附件列表
        annexList:[],
        //备注
        remarks: ''
      },
      // 表格多选
      multipleSelection: [],
      multipleAccountStatus: [],
      multipleAccountId: [],
      //
      btnLock: false,
      saveLoading: false,
      auditLoading: false,
      // 是否编辑
      isEdit: false,
      // 预览
      previewDialog: false,
      // 当前账户下可选用户
      optimizedList: [],
      designerList: [],
      imageUpload: true,
      imageUploadId: false,
      fileMap: {},
      tickSeq: 1,
      isExistsAppUrl: false,
      successAndNotExists: null,

      relatesInformation: false,
      addOfferVisible: false,
      addOfferBtn: false,
      active: 0,
      appDTO: {},
      offer: {},
      offerForm: {
        offerId: '',
        operator: '',
        user: '',
      },
      addOfferForm: {
        offerName: '',
        productName: '',
        customer: '',
        adAuditCreative: 0,
        optimized: '',
        designer: '',
        nation: '',
        //工作室
        studio:''
      },
      addEntityNameVisible: false,
      addEntityNameForm: {
        name: ''
      },
      entityId: '',
      isEditEntity: true,
      entityNameRule: [{validator: validateEntityName, trigger: 'blur'}],
      currentRow: {},
      // 工作室媒体数据
      mediaList:[
        {
          value: 'tiktok',
          label: 'Tiktok'
        },
        {
          value: 'facebook',
          label: 'Facebook'
        },
        {
          value: 'google',
          label: 'Google'
        },
        {
          value: 'kwai',
          label: 'Kwai'
        },
        {
          value: 'bigo',
          label: 'BigoAds'
        },
      ],
      studioList:[
        {
          value: 0,
          label: 'EGM'
        },
        {
          value: 1,
          label: 'BPC'
        },
        {
          value: 2,
          label: 'BOP'
        },
        {
          value: 3,
          label: 'MOT'
        },
        {
          value: 4,
          label: 'GLG'
        },
      ],
    }
  },
  created() {
    // await this.getAccountList()
    this.getAccountList()
    this.getCreateUserList()
    this.getCustomerList()
    this.getTimeZone()
    this.getIndustry()
    this.getNationList()
    this.getWorkrooms()
    this.getUser()
    this.loading = false
  },
  methods: {
    //开户类型选择
    accountTypeChange(value){
      if(this.accountForm.platform == 'facebook'  && value !== '国内代理'){
        this.$refs.accountForm.rules.licenseNo=[];
        this.$refs.accountForm.rules.licenseImage=[];
        this.$refs.accountForm.clearValidate(['licenseNo'])
        this.$refs.accountForm.clearValidate(['licenseImage'])
      }else{
        this.$refs.accountForm.rules.licenseNo=[{required: true, message: '请输入营业执照编号', trigger: 'blur'}];
        this.$refs.accountForm.rules.licenseImage=[{required: true, message: "请上传营业执照", trigger: "blur"}]
      }
      // this.$nextTick(() => { this.$refs.accountForm.clearValidate(['licenseNo'])});
      console.log(this.$refs.accountForm.rules)
    },
    //图片下载
    licenseImageDownload(url){
      var filename = this.accountForm.entityName;
      var urltype = url.split('.')
      const promise = this
        .downloadUrlQiniu(
          url
        )
        .then((res) => {
          var blob = new Blob([res]);
          FileSaver.saveAs(
            blob,
            filename + '.'  + urltype[urltype.length - 1]
          );

        })
        .catch((error) => {
          console.log(error)
        });


    },
    downloadUrlQiniu(url) {
      return new Promise((resolve, reject) => {
        if (!url.startsWith("http")) {
          return;
        }
        if (!url.startsWith("https")) {
          let urlArr = url.split("://");
          if (urlArr.length < 2) {
            return;
          }
          url = "https://" + urlArr[1];
        }
        // url = getCrossUrl(url)
        fetch(url, {
          method: "GET",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
          },
        })
          .then((res) => {
            resolve(res.blob());
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    //图片放大
    enlargeImage(url){
      this.imgDialog=true;
      this.previewUrl=url
    },
    uploadFinished(url,uplodParame) {
      if(uplodParame=='license'){
        this.accountForm.licenseImage = url;
      }else if(uplodParame=='website'){
        this.accountForm.websiteScreenshot = url;
      }else if(uplodParame=='annex'){
        this.accountForm.annexList.push(url)
      }
    },
    fileDeleted(url,uplodParame) {
      if(uplodParame=='license'){
        this.accountForm.licenseImage = '';
      }else if(uplodParame=='website'){
        this.accountForm.websiteScreenshot = '';
      }else if(uplodParame=='annex'){
        let index = this.accountForm.annexList.indexOf(url);
        this.accountForm.annexList.splice(index, 1)
      }
    },
    callbackFunc(url) {
      this.accountForm.licenseImage = url
    },
    clearCustomerFullName() {
      this.accountForm.customerName = ""
      this.accountForm.customerFullName = ""
      this.accountForm.entityName = ""
      this.accountForm.licenseImage = ""
      this.accountForm.licenseNo = ""
      this.accountForm.baseName = "ads4each-[产品名称]-[公司简称]"
    },
    clearEntityName() {
      this.accountForm.entityName = ""
      this.accountForm.licenseImage = ""
      this.accountForm.licenseNo = ""
    },
    // 改变主体
    handleChangeEntity(val) {
      this.renderlicenseImage()
      const cur = this.accountEntityList.find(item => item.entityName === val)
      if (cur !== undefined) {
        this.entityId = cur.id
      } else {
        this.entityId = ''
      }
    },
    //清空表单方法
    initAccountForm(){
      this.accountForm.customerName= '',
        this.accountForm.customerId= 1,
        this.accountForm.customerFullName= '',
        this.accountForm.entityId= null,
        this.accountForm.entityName= '',
        this.accountForm.timezone= '',
        this.accountForm. baseName= 'ads4each-[产品名称]-[公司简称]',
        this.accountForm.number= 1,
        this.accountForm.licenseNo= '',
        this.accountForm.appLink= '',
        this.accountForm.licenseImage= '',
        this.accountForm.industry= '',
        this.accountForm.prepareRechargeAmount= 0,
        this.industryList = [],
        this.nationList = [],
        this.KBnationList =[],
        this.accountForm.multipleRegisteredArea=[]
        //推广链接是否地域访问限制
        this.accountForm.geoLimit= 0,
        //fbAppId
        this.accountForm.fbAppId='',
        // 投放地区
        this.accountForm.registeredArea='',
        // 开户类型
        this.accountForm.accountType='国内代理',
        //币种
        this.accountForm.currency='USD',
        //备注
        this.accountForm.remarks='',
        //附件列表
        this.accountForm.annexList=[],
        //网站截图
        this.accountForm.websiteScreenshot=''
      this.imageUrl = ''
      this.dialogForm.name = null
      this.dialogForm.appPackageId = null
      this.dialogForm.category = null
      this.addLoading = false

      this.drawerTitle = '新增开户申请'
      this.accountForm.id = null
      this.drawerSwitch = true
      // console.log(this.$refs.fileUploader)
      if (this.$refs.fileUploader === undefined) return
      this.$refs.fileUploader.reset();
      // this.$refs.fileUploaders.reset()
      // this.$refs.fileUploaderWeb.reset()
    },
    renderlicenseImage() {
      getAccountEntityList(
        this.customerList.find(item => item.label === this.accountForm.customerName)['value']).then(res => {
        this.accountEntityList = res.data.data
        let img = this.accountEntityList.find(item => item.entityName === this.accountForm.entityName)
        if (img !== undefined && img !== null) {
          let entity = _.cloneDeep(img)
          this.accountForm.appLink = entity.appLink
          this.accountForm.entityName = entity.entityName
          this.accountForm.licenseImage = entity.licenseImage
          this.accountForm.licenseNo = entity.licenseNo
          this.accountForm.baseName = entity.baseName
        } else {
          this.accountForm.licenseImage = ""
          this.accountForm.licenseNo = ""
        }
      })
    },
    defaultNumber(val) {
      if (val < 0) {
        this.accountForm.number = 1
      }
    },
    defaultprepareRechargeAmount(val) {
      if (val < 0) {
        this.accountForm.prepareRechargeAmount = 0
      }
    },
    handleChangeFilter(val) {
      this.loading = true
      this.query = val
      // console.log(this.query)
      this.page.current = 1
      this.getAccountList();
      this.loading = false
    },
    // 新增
    addAccount() {
      this.currencyList=[
        {
          value:'USD',
          label:'USD'
        }
      ];
      this.nationList = this.ttNationList
      this.industryList = this.ttIndustryList
      this.imageUrl = ''
      this.accountForm = {
        multipleRegisteredArea:[],
        customerName: '',
        customerId: 1,
        customerFullName: '',
        entityId: null,
        entityName: '',
        timezone: '',
        baseName: 'ads4each-[产品名称]-[公司简称]',
        number: 1,
        licenseNo: '',
        appLink: '',
        licenseImage: '',
        industry: '',
        prepareRechargeAmount: 0,
        platform:'tiktok',
        //推广链接是否地域访问限制
        geoLimit:0,
        //fbAppId
        fbAppId:'',
        // 投放地区
        registeredArea:'',
        // 开户类型
        accountType: '国内代理',
        //币种
        currency:'USD',
        //备注
        remarks:'',
        //网站截图
        websiteScreenshot:'',
        annexList:[]
      };
      this.dialogForm.name = null
      this.dialogForm.appPackageId = null
      this.dialogForm.category = null
      this.addLoading = false

      this.drawerTitle = '新增开户申请'
      this.accountForm.id = null
      this.drawerSwitch = true
      // console.log(this.$refs.fileUploader)
      if (this.$refs.fileUploader === undefined) return
      this.$refs.fileUploader.reset()
    },
    findTimezone(val) {
      try {
        return this.timeZoneList.find(item => item.dictKey === val)['dictValue']
      } catch (e) {
        return ''
      }
    },
    findUser(val) {
      try {
        return this.createUserList.find(item => item.id === val)['realName']
      } catch (e) {
        return ''
      }
    },
    findStatus(val) {
      try {
        return this.statusList.find(item => item.value === val)['label']
      } catch (e) {
        return ''
      }
    },
    findDept(val) {
      try {
        if(val == -1) throw ''
        else  throw this.deptList.find(item => item.value === val)['label']

      } catch (e) {
        return e
      }
    },
    uploadQiniuCloud(file) {
      const that = this
      const fileData = qiniuTools.getFileData(file)
      const callback = {
        next(res) {
        },
        error(err) {
          this.$message.error("上传图片失败! err => " + err);
        },
        complete(res) {
          const url = 'http://' + fileData.server + '/' + res.key
          that.$set(that, 'imageUrl', url)
          // that.logoUrl = url
        }
      }
      const uploader = qiniuTools.uploadQiniuCloud(file, fileData)
      uploader.subscribe(callback)
    },
    beforeAvatarUpload(file) {
      var img = file.name.substring(file.name.lastIndexOf('.') + 1)
      const suffix = img === 'jpg'
      const suffix2 = img === 'png'
      const suffix3 = img === 'jpeg'
      const isLt1M = file.size / 1024 / 1024 < 1;
      if (!suffix && !suffix2 && !suffix3) {
        this.$message.error("只能上传图片！");
        return false
      }
      // 可以限制图片的大小
      if (!isLt1M) {
        this.$message.error('上传图片大小不能超过 1MB!');
      }
      return suffix || suffix2 || suffix3
    },
    async checkLicenseNoExist(id, val) {
      if (this.drawerTitle === '编辑') return
      const {data: res} = await checkLicenseNoExist(id, val)
      return res.data
    },
    async changeFullName(val) {
      const {data: res} = await getAccountEntityList(this.customerList.find(item => item.label === val)['value'])
      this.accountEntityList = res.data
      let baseName = this.accountForm.baseName.substring(0, this.accountForm.baseName.lastIndexOf('-') + 1)
      this.accountForm.baseName = baseName + val
      this.accountForm.customerFullName = this.customerList.find(item => item.label === this.accountForm.customerName)['fullName']
      this.clearEntityName()
    },
    async changeAccountName(val) {
      if (val === '') return
      const {data: res} = await getAppInfo(this.accountForm.appLink)
      let productName = '';
      if (res.code === 500) {
        this.successAndNotExists = false
      } else {
        this.successAndNotExists = true
        this.appInfo = res.data.appInfo
        productName = res.data.appInfo.productName
        this.pullproductName = res.data.appInfo.productName
        // this.verifyUrl = false
        // console.log('aaa',productName)
        let prefixName = this.accountForm.baseName.substring(0, this.accountForm.baseName.indexOf('-') + 1)
        let baseName = this.accountForm.baseName.substring(this.accountForm.baseName.lastIndexOf('-'), this.accountForm.baseName.length)
        this.accountForm.baseName = prefixName + productName + baseName
      }
      if (res.data.isExistsAppUrl) {
        this.isExistsAppUrl = true
      } else {
        this.isExistsAppUrl = false
      }

      // if (res.code === 200 && res.data.getTtApiFail) {
      //   this.$message.warning('无法拉取该推广链接的产品名称，请自行配置账户命名中的[产品名称]！')
      // }
      //拉不到且不存在
      // if (!res.data.isExistsAppUrl && res.data.getTtApiFail){
      //   this.successAndNotExists = false
      // }
      // if (res.data.isExistsAppUrl){
      //   this.verifyUrl = false
      // }else{
      //   this.verifyUrl = true
      // }
      // this.appInfo = res.data.appInfo
      // productName = res.data.appInfo.productName
      // this.pullproductName = res.data.appInfo.productName
      // // this.verifyUrl = false
      // // console.log('aaa',productName)
      // let prefixName = this.accountForm.baseName.substring(0, this.accountForm.baseName.indexOf('-') + 1)
      // let baseName = this.accountForm.baseName.substring(this.accountForm.baseName.lastIndexOf('-'), this.accountForm.baseName.length)
      // this.accountForm.baseName = prefixName + productName + baseName
    },
    //切换开户媒体
    mediaChange(value){
      //防止验证切换
      this.$refs["accountForm"].clearValidate();
      this.initAccountForm();
      this.accountForm.geoLimit=0,
        this.accountForm.licenseImage=''
      this.accountForm.licenseImage=''
      this.accountForm.websiteScreenshot=''
      if(value == 'facebook')
        this.currencyList=[
          {
            value:'USD',
            label:'USD'
          },
          {
            value:'ARS',
            label:'ARS'
          },
          {
            value:'NGN',
            label:'NGN'
          },
        ];
      else if(value == 'google'){ this.currencyList=[
          {
            value:'USD',
            label:'USD'
          },
          {
            value:'ARS',
            label:'ARS'
          },
          {
            value:'NGN',
            label:'NGN'
          },
        ];
        this.accountForm.baseName='ads4each-[产品名称]'
      }
      else if (value == 'tiktok') {
        this.currencyList=[
          {
            value:'USD',
            label:'USD'
          }
        ];
        this.nationList = this.ttNationList
        this.industryList = this.ttIndustryList
      } else if (value == 'bigo') {
        this.currencyList=[
          {
            value:'USD',
            label:'USD'
          }
        ];
        this.KBnationList = this.bigoNationList
        // console.log(this.nationList)
        this.industryList = this.bigoIndustryList
      } else if (value == 'kwai') {
        this.currencyList=[
          {
            value:'USD',
            label:'USD'
          }
        ];
        this.KBnationList = this.kwaiNationList
        this.industryList=this.kwaiIndustryList
      }

    },
    //币种选择
    currencyChange(value){
      this.accountForm.currency=value
    },
    saveApp() {
      if (this.dialogForm.name === null) {
        return this.$message.warning('请选择填写产品名称！')
      }
      // this.addLoading = true
      let data = {
        appUrl: this.dialogForm.appUrl,
        impressionMonitorUrl: this.dialogForm.impressionMonitorUrl,
        clickMonitorUrl: this.dialogForm.clickMonitorUrl,
        customerId: this.customerList.find(item => item.label === this.dialogForm.customerId)['value'],
        name: this.dialogForm.name,
        os: this.dialogForm.os,
        appPackageId: this.dialogForm.appPackageId,
        // isWebsite: this.dialogForm.isWebsite,
        category: this.dialogForm.category,
        imageUrl: this.imageUrl
      }
      addApp(data).then(res => {
        if (res.data.data) {
          let message = '操作成功';
          if (res.data.msg != null && res.data.msg != '') {
            message = res.data.msg;
          }
        }
        // this.verifyUrl = true
        this.dialogFormVisible = false
        if (this.addOrSubmit) {
          this.addSave()
        } else {
          this.saveAndAudit()
        }
      }).catch(error => {
        if (error) {
          this.addLoading = false
        }
      })
    },
    iHeaderCellStyle() {
      return {
        color: '#101010',
        backgroundColor: '#F2F2F2'
      }
    },

    handleSelectionChange(val) {
      this.multipleSelection = val.map(item => item.id)
      this.multipleSelection1 = val.map(item => item.status);
    },
    selectionChange(val) {
      this.multipleAccountStatus = val.map(item => item.status)
      this.multipleAccountId = val.map(item => item.account_id)
    },
    handleSizeChange(val) {
      this.page.size = val
      this.getAccountList()
    },
    handleCurrentChange(val) {
      this.page.current = val
      this.getAccountList()
    },

    async showAccountOpen(row) {
      console.log(row)
      this.accountForm.registeredArea=''
      this.drawerTitle = '查看'
      this.drawerSwitch = true;
      const {data: res} = await getRecordNodeList(row.id)
      this.recordNode = res.data
      debugger
      if(row.platform=='tiktok'){
        this.accountForm.registeredArea = row.registeredArea
        this.accountForm.industry = row.industry
      }else if(row.platform=='kwai'){
        this.KBnationList = this.kwaiNationList
        this.accountForm.multipleRegisteredArea = row.registeredArea.split(',')
        this.accountForm.industry = row.industry.split(',')
      }else  if(row.platform=='bigo'){
        this.KBnationList = this.bigoNationList
        this.accountForm.multipleRegisteredArea = row.registeredArea.split(',')
        this.accountForm.industry = row.industry
      }
      if(row.platform=='kwai'){
        this.accountForm.timezone=''
      }else{
        this.accountForm.timezone = row.timezone;
      }
      // this.accountForm = row;
      this.accountForm.customerName = row.customerName;
      this.accountForm.customerId = row.customerId;
      this.accountForm.customerFullName = row.customerFullName;
      // this.accountForm.timezone = row.timezone;
      // this.accountForm.registeredArea = row.registeredArea;
      this.accountForm.baseName = row.baseName;
      this.accountForm.number = row.number;
      this.accountForm.licenseNo = row.licenseNo;
      this.accountForm.currency = row.currency
      this.accountForm.appLink = row.appLink;
      this.accountForm.licenseImage = row.licenseImage;
      this.accountForm.status = row.status;
      this.accountForm.prepareRechargeAmount = row.prepareRechargeAmount
      this.accountForm.entityName = row.entityName

      this.relativeAccounts = row.relativeAccounts
      //新增四家参数
      this.accountForm.platform = row.platform
      this.accountForm.geoLimit = row.geoLimit
      this.accountForm.fbAppId = row.fbAppId
      this.accountForm.accountType = row.accountType
      this.accountForm.currency = row.currency
      this.accountForm.websiteScreenshot = row.websiteScreenshot
      if(row.accessory==''){
        this.accountForm.annexList=[]
      }else{
        this.accountForm.annexList = row.accessory.split(',')
      }
      this.accountForm.remarks = row.remarks
      // this.$refs.fileUploader.reset()
    },
    //新建并提审
    async saveAndAudit() {
      this.addOrSubmit = false
      // if (this.accountForm.licenseImage === '') {
      //   this.$message.error("请上传营业执照");
      //   return;
      // }
      let entity = this.accountEntityList.find(item => item.entityName === this.accountForm.entityName)
      if (entity != null) {
        this.accountForm.entityId = entity.id
      }
      if (!['google','bigo'].includes(this.accountForm.platform)){
        let licenseExist = await this.checkLicenseNoExist(this.accountForm.entityId, this.accountForm.licenseNo)
        if (licenseExist) {
          this.$message.error("营业执照编号已被使用，无法开户！");
          return;
        }
      }
      this.$refs.accountForm.validate((valid) => {
        if (valid) {
          this.auditLoading = true
          this.changeAccountName().finally(async () => {
            this.addAndCopySubmitAudit = true
            this.auditLoading = false
            if (!this.successAndNotExists) {
              this.active = 0
            } else {
              this.active = 1
              //
              this.appDTO = {
                customerId: this.customerList.find(item => item.label === this.accountForm.customerName)['customerId'],
                isWebsite: false,
                appUrl: this.accountForm.appLink,
                name: this.appInfo.productName,
                os: this.appInfo.os,
                appPackageId: this.appInfo.packageName,
                category: this.appInfo.category,
                imageUrl: this.appInfo.logoUrl
              }
            }
            this.relatesInformation = true

            // if (this.verifyUrl){
            //   this.dialogFormVisible = true
            //   this.dialogForm.appUrl = this.accountForm.appLink
            //   // console.log('ss',this.accountForm.customerName)
            //   this.dialogForm.customerId = this.accountForm.customerName
            //   // this.dialogForm.customerId = this.customerList.find(item=>item.label === this.accountForm.customerName)['customerId']
            //   return
            // }
            // let entity = this.accountEntityList.find(item=>item.entityName===this.accountForm.entityName)
            // if (entity != null) {
            //   this.accountForm.entityId = entity.id
            // }
            // this.loading = true
            // const {data: res} = await saveAndAudit(this.getReportForm()).finally(() => this.loading = false)
            // console.log('保存', res)
            // if (res.code !== 200) {
            //   return this.$message.error('提交审核失败')
            // }
            // this.$message.success('提交审核成功')
            // this.closeDrawer()
            // await this.getAccountList()

          })

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    closeDrawer() {
      this.drawerSwitch = false
      this.btnLock = false
      this.loading = false
      this.drawerTitle = ''
      this.editSaveStatus = true
    },
    getAccountList() {
      getAccountList(this.query, this.page).then(res => {
        this.total = res.data.data.total
        this.accountList = res.data.data.records
        this.loading = false
      })
    },
    getCreateUserList() {
      getCreateUser().then(res => {
        this.createUserList = res.data.data
      })
    },
    getCustomerList() {
      getCustomer().then(res => {
        this.customerList = res.data.data.map(item => {
          return {
            value: item.key,
            label: item.name,
            fullName: item.data,
          }
        })
      })
    },
    websiteControl() {
      // if (this.dialogForm.isWebsite) {
      //   this.normalHisAppUrl = this.dialogForm.appUrl
      //   this.dialogForm.appUrl = this.websiteHisAppUrl
      // } else {
      //   this.websiteHisAppUrl = this.dialogForm.appUrl
      //   this.dialogForm.appUrl = this.normalHisAppUrl
      // }
    },
    async addSave() {
      this.addOrSubmit = true
      // this.changeAccountName()
      let entity = this.accountEntityList.find(item => item.entityName === this.accountForm.entityName)
      if (entity != null) {
        this.accountForm.entityId = entity.id
      }
      if (!['google','bigo'].includes(this.accountForm.platform)){
        let licenseExist = await this.checkLicenseNoExist(this.accountForm.entityId, this.accountForm.licenseNo)
        if (licenseExist) {
          this.$message.error("营业执照编号已被使用，无法开户！");
          return;
        }
      }
      this.$refs.accountForm.validate(valid => {
        if (valid) {
          this.saveLoading = true
          this.changeAccountName().finally(() => {
            this.saveLoading = false
            if (!this.successAndNotExists) {
              this.active = 0
            } else {
              this.active = 1
              // this.appDTO = deepClone(this.appInfo)
              this.dialogForm
              this.appDTO = {
                customerId: this.customerList.find(item => item.label === this.accountForm.customerName)['customerId'],
                isWebsite: false,
                appUrl: this.accountForm.appLink,
                name: this.appInfo.productName,
                os: this.appInfo.os,
                appPackageId: this.appInfo.packageName,
                category: this.appInfo.category,
                imageUrl: this.appInfo.logoUrl
              }
            }
            this.relatesInformation = true
            // if (this.verifyUrl){
            //   this.dialogFormVisible = true
            //   this.dialogForm.appUrl = this.accountForm.appLink
            //   this.dialogForm.customerId = this.accountForm.customerName
            //   return
            // }
            // let entity = this.accountEntityList.find(item=>item.entityName===this.accountForm.entityName)
            // if (entity != null) {
            //   this.accountForm.entityId = entity.id
            // }
            // this.loading = true
            // save(this.getReportForm()).then(result => {
            //   this.loading = false
            //   if (result.data.code != 200) {
            //     this.dialogForm.name = ''
            //     return this.$message.error('保存失败')
            //   } else {
            //     this.$message.success('保存成功')
            //     this.getAccountList()
            //     this.dialogForm.name = ''
            //     this.closeDrawer()
            //   }
            // })
          })

          // if (this.verifyUrl){
          //   this.dialogFormVisible = true
          //   this.dialogForm.appUrl = this.accountForm.appLink
          //   this.dialogForm.customerId = this.accountForm.customerName
          //   return
          // }

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    refreshAccount() {
      this.loading = true
      this.getAccountList()
    },

    async editAccount() {
      if (this.accountForm.licenseImage === '') {
        this.$message.error("请上传营业执照");
        return;
      }
      if (this.accountForm.licenseImage === '' && !this.$refs.fileUploader.uploadCompleted()) {
        this.$message.error("营业执照尚未上传完成");
        return;
      }
      if (!['google','bigo'].includes(this.accountForm.platform)){
        let licenseExist = await this.checkLicenseNoExist(this.accountForm.entityId, this.accountForm.licenseNo)
        if (licenseExist) {
          this.$message.error("营业执照编号已被使用，无法开户！");
          return;
        }
      }
      this.$refs.accountForm.validate(async (valid) => {
        if (valid) {

          let entity = this.accountEntityList.find(item => item.entityName === this.accountForm.entityName)
          if (entity != null) {
            this.accountForm.entityId = entity.id
          }
          this.loading = true
          if (this.drawerTitle === "编辑") {
            const {data: res} = await updateAudit(this.getReportForm()).finally(() => this.loading = false)
            if (res.code !== 200) {
              this.loading = false
              return this.$message.error('保存失败')
            } else {
              this.$message.success('保存成功')
            }
          } else {
            this.addSave()
            // this.changeAccountName(this.accountForm.appLink).finally(async()=>{
            //   const {data: res} = await save(this.getReportForm()).finally(() => this.loading = false)
            //   if (res.code !== 200) {
            //     this.loading = false
            //     return this.$message.error('保存失败')
            //   } else {
            //     this.$message.success('保存成功')
            //   }
            // })
          }
          // console.log('保存', res)
          await this.getAccountList()
          this.closeDrawer()

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    async updateAndAudit() {
      if(['tiktok','facebook','kwai','bigo'].includes(this.accountForm.platform)){
        if (this.accountForm.licenseImage === '') {
          this.$message.error("请上传营业执照");
          return;
        }else if(this.accountForm.licenseImage === '' && !this.$refs.fileUploader.uploadCompleted()){
          this.$message.error("营业执照尚未上传完成");
          return;
        }
      }
      let entity = this.accountEntityList.find(item => item.entityName === this.accountForm.entityName)
      if (entity != null) {
        this.accountForm.entityId = entity.id
      }
      if (!['google','bigo'].includes(this.accountForm.platform)){
        let licenseExist = await this.checkLicenseNoExist(this.accountForm.entityId, this.accountForm.licenseNo)
        if (licenseExist) {
          this.$message.error("营业执照编号已被使用，无法开户！");
          return;
        }
      }
      this.$refs.accountForm.validate(async (valid) => {
        if (valid) {
          let entity = this.accountEntityList.find(item => item.entityName === this.accountForm.entityName)
          if (entity != null) {
            this.accountForm.entityId = entity.id
          }
          this.loading = true
          if (this.drawerTitle === "编辑") {
            const {data: res} = await updateAndAudit(this.getReportForm()).finally(() => this.loading = false)
            if (res.code !== 200) {
              this.loading = false
              return this.$message.error('保存失败')
            } else {
              this.$message.success('保存成功')
            }
          } else {
            const {data: res} = await save(this.getReportForm()).finally(() => this.loading = false)
            if (res.code !== 200) {
              this.loading = false
              return this.$message.error('保存失败')
            } else {
              this.$message.success('保存成功')
            }
          }
          // console.log('保存', res)
          await this.getAccountList()
          this.closeDrawer()
        } else {
          console.log('error submit!!');
          return false;
        }
      });


    },

    async editOrCopyReportNew(row, title) {
      this.currentRow = row
      this.imageUrl = ''
      this.copyProductName = row.productName
      if (row.status === 2) {
        this.editSaveStatus = false
      }
      debugger
      const origin = deepClone(row)
      this.drawerTitle = title
      this.drawerSwitch = true
      if (title == "编辑")
      this.accountForm.id = origin.id;
      this.accountForm.customerName = origin.customerName;
      this.accountForm.customerId = origin.customerId;
      this.accountForm.customerFullName = origin.customerFullName;
      this.accountForm.timezone = origin.timezone;
      this.accountForm.baseName = origin.baseName;
      this.accountForm.number = origin.number;
      this.accountForm.licenseNo = origin.licenseNo;
      this.accountForm.currency = origin.currency
      this.accountForm.appLink = origin.appLink;
      this.accountForm.licenseImage = origin.licenseImage;
      this.accountForm.status = origin.status;
      this.accountForm.prepareRechargeAmount = origin.prepareRechargeAmount
      this.accountForm.entityName = origin.entityName
      if(origin.platform == 'kwai'){
        this.accountForm.industry = origin.industry.split(',')
      }else{
        this.accountForm.industry = origin.industry
      }
      //新增四家参数
      this.accountForm.platform = origin.platform
      this.accountForm.geoLimit = origin.geoLimit
      this.accountForm.fbAppId = origin.fbAppId
      this.accountForm.accountType = origin.accountType
      this.accountForm.currency = origin.currency
      this.accountForm.websiteScreenshot = origin.websiteScreenshot
      if (origin.accessory != '')
        this.accountForm.annexList = origin.accessory.split(',')
      else
        this.accountForm.annexList=[]
      this.accountForm.remarks = origin.remarks
      const {data: res} = await getAccountEntityList(this.customerList.find(item => item.label === row.customerName)['value'])
      this.accountEntityList = res.data
      if(origin.platform == 'facebook'){
        this.currencyList=[
          {
            value:'USD',
            label:'USD'
          },
          {
            value:'ARS',
            label:'ARS'
          },
          {
            value:'NGN',
            label:'NGN'
          },
        ];
        this.$refs.fileUploader.reset()
        this.$refs.fileUploaderWeb.reset()
      } else if(origin.platform == 'kwai'){
        this.currencyList=[
          {
            value:'USD',
            label:'USD'
          }
        ];
        this.KBnationList = this.kwaiNationList
        this.industryList=this.kwaiIndustryList
        this.accountForm.multipleRegisteredArea = origin.registeredArea.split(',')
        this.$refs.fileUploader.reset()
      }
      else if(origin.platform == 'bigo'){
        this.currencyList=[
          {
            value:'USD',
            label:'USD'
          },
          {
            value:'ARS',
            label:'ARS'
          },
          {
            value:'NGN',
            label:'NGN'
          },
        ];
        this.currencyList=[
          {
            value:'USD',
            label:'USD'
          }
        ];
        this.KBnationList = this.bigoNationList
        this.industryList = this.bigoIndustryList
        this.accountForm.multipleRegisteredArea = origin.registeredArea.split(',')
        this.$refs.fileUploader.reset()
      } else if(origin.platform == 'google'){
        this.currencyList=[
          {
            value:'USD',
            label:'USD'
          },
          {
            value:'ARS',
            label:'ARS'
          },
          {
            value:'NGN',
            label:'NGN'
          },
        ];
      }
      else {
        this.currencyList=[
          {
            value:'USD',
            label:'USD'
          }
        ];
        this.nationList = this.ttNationList
        this.multiple=false
        this.industryList = this.ttIndustryList
        this.accountForm.registeredArea = origin.registeredArea;
        this.$refs.fileUploader.reset()
      }
      if(this.$refs.accountForm.rules.licenseNo.length === 0){
        this.$refs.accountForm.rules.licenseNo=[{required: true, message: '请输入营业执照编号', trigger: 'blur'}];
        this.$refs.accountForm.rules.licenseImage=[{required: true, message: "请上传营业执照", trigger: "blur"}]
      }

    },
    getReportForm() {
      debugger
      let industry='';
      let registeredArea=''
      if (this.accountForm.platform=='tiktok'){
        registeredArea= this.accountForm.registeredArea
      }else if(['kwai','bigo'].includes(this.accountForm.platform)){
        registeredArea=this.accountForm.multipleRegisteredArea.join(',')
      }else{
        registeredArea=''
      }
      if (this.accountForm.platform=='kwai'){
        industry= this.accountForm.industry.join(',')
      }else{
        industry=this.accountForm.industry
      }
      let data = {
        id: this.accountForm.id,
        customerName: this.accountForm.customerName,
        customerFullName: this.accountForm.customerFullName,
        timezone: this.accountForm.timezone,
        registeredArea: registeredArea,
        baseName: this.accountForm.baseName,
        number: this.accountForm.number,
        licenseNo: this.accountForm.licenseNo,
        appLink: this.accountForm.appLink,
        licenseImage: this.accountForm.licenseImage,
        industry: industry,
        customerId: this.customerList.find(item => item.label === this.accountForm.customerName)['value'],
        currency: this.accountForm.currency,
        prepareRechargeAmount: this.accountForm.prepareRechargeAmount,
        entityId: this.accountForm.entityId,
        entityName: this.accountForm.entityName,
        productName: this.pullproductName === '' ? this.dialogForm.name : this.pullproductName,
        platform: this.accountForm.platform,
        geoLimit: this.accountForm.geoLimit,
        fbAppId: this.accountForm.fbAppId,
        accountType: this.accountForm.accountType,
        websiteScreenshot: this.accountForm.websiteScreenshot,
        remarks: this.accountForm.remarks,
        accessory: this.accountForm.accessory,
      }
      return data
    },
    async deleteAccount(id) {
      this.$confirm('是否刪除?', '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const {data: res} = await removeAccountByIds(id)
        if (res.code !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        await this.getAccountList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //删除多个提交申请
    deleteAccounts(){
      let ids=this.multipleSelection.join(',')
      this.deleteAccount(ids)
    },
    //多选提交
    async selectionSubmitAudit() {
      // const {data: res} = await submitAudit(this.multipleSelection)
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请至少选择一条')
        return;
      }
      // if(!this.multipleSelection1.indexOf('0')){
      //   this.$message.warning('草稿状态才可提交')
      //   return;
      // }
      let res = null
      for (let i = 0; i < this.multipleSelection.length; i++) {
        const {data: res} = await submitAudit(this.multipleSelection[i])
      }
      if (res && res.code !== 200) return this.$message.error('提交失败')
      this.$message.success('提交审核成功')
      await this.getAccountList()
    },
    submitAudit() {
      this.$refs.datailForm.validate(async (valid) => {
        if (valid) {
          if (this.datailForm.status === 1) {
            this.$message.error("正在申请中");
            return;
          }
          // alert('submit!');
          this.loading = true
          const {data: res} = await submitAudit(this.datailForm.id).finally(() => this.loading = false)
          if (res.code !== 200) {
            this.loading = false
            return this.$message.error('提交失败')
          } else {
            this.loading = false
            this.$message.success('提交成功')
            await this.getAccountList()
            this.btnLock = false
          }

        } else {
          console.log('error submit!!');
          return false;
        }
      });

    },
    //素材详细
    handlePictureCardPreview(v) {
      if (v.type === 'image') {
        this.dialogType = 'image'
      } else if (v.type === 'video') {
        this.dialogType = 'video'
      }
      this.dialogImageUrl = v.url;
      this.dialogVisible = true;
    },
    //删除
    handleRemove(v) {
      // this.$refs.fileUploader
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$refs.fileUploader.removeByUid(v.uid);
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleClose() {
      this.dialogVisible = false
      this.dialogFormVisible = false
      // this.$refs.video.pause();
    },
    handleCloseRelates() {
      this.relatesInformation = false
    },
    next() {
      this.$refs.appForm.validate(valid => {
        if (valid) {
          this.appDTO = {
            appUrl: this.dialogForm.appUrl,
            impressionMonitorUrl: this.dialogForm.impressionMonitorUrl,
            clickMonitorUrl: this.dialogForm.clickMonitorUrl,
            customerId: this.dialogForm.customerId,
            name: this.dialogForm.name,
            os: this.dialogForm.os,
            appPackageId: this.dialogForm.appPackageId,
            // isWebsite: this.dialogForm.isWebsite,
            category: this.dialogForm.category,
            imageUrl: this.imageUrl
          }
          this.active = 1

        }
      })

    },
    prev() {
      this.active = 0
    },
    accountChangeOffer() {
      this.offer = undefined
    },
    saveRelateMsg() {
      this.$refs.accountMsgForm.validate(valid => {
        if (valid) {
          if (this.relatesSaveLoading) return
          this.relatesSaveLoading = true
          //保存账户信息
          let agencyName = ''
          if (['tiktok','kwai','bigo'].includes(this.accountForm.platform)) {
            agencyName = 'Ads4each'
          }
          if(this.offerForm.offerId != this.addOfferForm.offerName){
            this.addOfferBtn=false
          }


          let account = {
            agencyName: agencyName,
            bindStatus: 0,
            name: '',
            platformId: '',
            offerId: this.addOfferBtn ? undefined : this.offerForm.offerId,
            operator: this.offerForm.operator,
            owner: this.offerForm.user,
            platform: this.accountForm.platform,
            status: 0
          }
          // batchAddAccounts(accountData).then(res => {
          //   console.log(res)
          // }).catch(()=>{
          //   this.$message.error('保存失败')
          // })
          let registeredArea=''
          let industry=''
          if(['kwai','bigo'].includes(this.accountForm.platform)){
            registeredArea=this.accountForm.multipleRegisteredArea.join(',')
          }else if(this.accountForm.platform == 'tiktok'){
            registeredArea=this.accountForm.registeredArea
          }else{
            registeredArea=''
          }
          if(this.accountForm.platform == 'kwai'){
            industry=this.accountForm.industry.join(',')
          }else{
            industry=this.accountForm.industry
          }
          let data = {
            id: this.accountForm.id,
            customerName: this.accountForm.customerName,
            customerFullName: this.accountForm.customerFullName,
            timezone: this.accountForm.timezone,
            registeredArea: registeredArea,
            baseName: this.accountForm.baseName,
            number: this.accountForm.number,
            licenseNo: this.accountForm.licenseNo,
            appLink: this.accountForm.appLink,
            licenseImage: this.accountForm.licenseImage,
            industry:industry,
            customerId: this.customerList.find(item => item.label === this.accountForm.customerName)['value'],
            currency: this.accountForm.currency,
            prepareRechargeAmount: this.accountForm.prepareRechargeAmount,
            entityId: this.accountForm.entityId,
            entityName: this.accountForm.entityName,
            //新增四家参数
            platform : this.accountForm.platform,
            geoLimit :  this.accountForm.geoLimit,
            fbAppId : this.accountForm.fbAppId,
            accountType :  this.accountForm.accountType,
            websiteScreenshot :  this.accountForm.websiteScreenshot,
            accessory :  this.accountForm.annexList.join(','),
            annexList :  this.accountForm.annexList,
            remarks :  this.accountForm.remarks,
            // productName:this.dialogForm.name===null ? this.copyProductName : this.dialogForm.name
            productName: this.pullproductName === '' ? this.dialogForm.name : this.pullproductName
          }
          if (!this.isExistsAppUrl) {
            data.appDTO = this.appDTO
          }
          if (this.addOfferBtn) {
            data.offer = this.offer
          }
          data.account = account
          console.log( this.addOfferBtn)
          if (this.addAndCopySubmitAudit) {
            saveAndAudit(data).then((res) => {
              this.$message.success('提交成功')
              this.relatesInformation = false
              this.drawerSwitch = false
              this.addOfferBtn=false
              this.getAccountList()
            }).catch(() => {
              this.$message.error('提交失败')
            }).finally(() => {
              this.relatesSaveLoading = false
            })
          } else {
            save(data).then((res) => {
              this.$message.success('保存成功')
              this.relatesInformation = false
              this.drawerSwitch = false
              this.addOfferBtn=false
              this.getAccountList()
            }).catch(() => {
              this.$message.error('保存失败')
            }).finally(() => {
              this.relatesSaveLoading = false
            })
          }


        }
      })
    },
    addOfferSave() {
      this.$refs.addOfferForm.validate(valid => {
        if (valid) {
          this.addOfferVisible = false
          this.addOfferBtn = true
          this.offerForm.offerId = this.addOfferForm.offerName
          this.offer = {
            name: this.addOfferForm.offerName,
            productName: this.addOfferForm.productName,
            customerId: this.addOfferForm.customer,
            isShared: this.addOfferForm.adAuditCreative,
            opUsers: this.addOfferForm.optimized,
            designers: this.addOfferForm.designer,
            nation: this.addOfferForm.nation.join(','),
            // androidAppId: "",
            // androidNation: '',
            androidPlatform: this.dialogForm.os === 2 ? '' : 'tiktok',
            // iosAppId: "",
            // iosNation: "",
            iosPlatform: this.dialogForm.os === 2 ? 'tiktok' : '',
            // websiteAppId: "",
            // websiteNation: "",
            websitePlatform: this.dialogForm.os === 3 ? 'tiktok' : '',
            team: this.addOfferForm.studio,
          }
        }
      })
    },
    // 账户名称
    formatterUserName(row, column, cellValue, index) {
      const temp = this.allUserList.find(item => item.id === cellValue)
      if (temp === undefined) {
        return ''
      } else {
        return temp.realName
      }
    },
    async getUser(){
      const res = await getAllUser({statusList: '0,1,2', isAll: true})
      this.allUserList = res.data.data
    },
    oppenRelatesInformation() {
      getOfferList().then(async res => {
        this.offerList = res.data.data
        if (this.drawerTitle === '编辑' || this.drawerTitle === '复制') {
          await this.getOfferDetail()
        }
      })
      // this.getUser()
      this.dialogForm.customerId = this.customerList.find(item => item.label === this.accountForm.customerName)['value']
      this.dialogForm.appUrl = this.accountForm.appLink
    },
    closeRelatesInformation() {
      this.successAndNotExists = null
      this.addAndCopySubmitAudit = false
      this.dialogForm = {
        customerId: null,
        isWebsite: false,
        appUrl: null,
        impressionMonitorUrl: null,
        clickMonitorUrl: null,
        name: null,
        os: null,
        os1: 2,
        // logoUrl: null,
        appPackageId: null,
        category: null,
        imageUrl: null
      }
      this.offerForm = {
        offerId: '',
        operator: '',
        user: '',
      }
      this.addOfferForm = {
        offerName: '',
        productName: '',
        customer: '',
        adAuditCreative: 0,
        optimized: '',
        designer: '',
      }
    },
    openAddOffer() {
      getOptimizer().then(res => {
        this.optimizedList = res.data.data
      })
      getDesignerSelect().then(res => {
        this.designerList = res.data.data
      })
      this.addOfferForm.productName = this.pullproductName === '' ? this.dialogForm.name : this.pullproductName
      this.addOfferForm.customer = this.customerList.find(item => item.label === this.accountForm.customerName)['value']
    },
    closeAddOffer() {
      // this.addOfferBtn = false
    },
    offerAccount() {
      if (this.relativeAccounts.length === 0) {
        return this.$message.warning('暂无账户信息')
      }
      if (this.multipleAccountStatus.length === 0) {
        return this.$message.warning('请勾选账户')
      }
      if (this.multipleAccountStatus.some(item => {
        return item !== 4
      })) {
        return this.$message.warning('只能一键关联媒体通过账户')
      }
      this.relativeAccountsId = this.relativeAccounts.map(item => item.account_id)
      // console.log(this.relativeAccountsId)
      this.$router.push({
        path: '/business/account',
        query: {
          data: this.multipleAccountId
        }
      })
    },
    cancel() {
      this.drawerSwitch = false
      this.editSaveStatus = true
    },
    getTimeZone() {
      getTimeZone().then(res => {
        this.timeZoneList = res.data.data
      })
    },

    getIndustry() {
      getTiktokIndustry().then(res => {
        let result = res.data.data
        result.forEach(item => {
          this.ttIndustryList.push({
            'dictKey': item.dictKey,
            'dictValue': item.dictValue
          })
        })
        this.industryList = this.ttIndustryList
      })

      getBigoIndustryList().then(res => {
        this.bigoIndustryList = res.data.data
      })
      getKwwaiIndustryList().then(res => {
        this.kwaiIndustryList = res.data.data
        console.log(this.kwaiIndustryList)
      })
    },
    getNationList() {
      //获取新增订单投放地区
      getGeoList().then(res => {
        this.orderNationList = res.data.data
      })
      getTiktokGeoList().then(res => {
        this.ttNationList = res.data.data
        this.ttNationList.forEach(item => {
          item.dictValue = item.dictValue + "(" + item.dictKey + ")"
        })
        this.nationList = this.ttNationList
      })
      getBigoGeoList().then(res => {
        this.bigoNationList = res.data.data
      })
      getKwaiGeoList().then(res => {
        this.kwaiNationList = res.data.data
      })
    },
    addEntityName() {
      this.$refs.addEntityNameForm.validate(async valid => {
        if (!valid) return
        if (this.isEditEntity) {
          await this.updateEntityName()
          getAccountEntityList(
            this.customerList.find(item => item.label === this.accountForm.customerName)['value']).then(res => {
            this.accountEntityList = res.data.data
          })
        } else {
          this.clearEntityName()
        }
        this.$set(this.accountForm, 'entityName', this.addEntityNameForm.name)
        this.addEntityNameVisible = false
        this.$refs.addEntityNameForm.resetFields()
      })
    },
    addEntity() {
      this.isEditEntity = false
      this.addEntityNameVisible = true
      this.addEntityNameForm.name = ''
    },
    editEntity() {
      this.isEditEntity = true
      this.addEntityNameVisible = true
      this.addEntityNameForm.name = this.accountForm.entityName
    },
    async updateEntityName() {
      await updateEntityName({
        entityId: this.entityId,
        entityName: this.addEntityNameForm.name
      })
    },
    // 获取订单APP详情
    async getOfferDetail() {
      const {data: res} = await getOfferDetailById(this.currentRow.id)
      // if (this.offerList.some(item => item.id == res.data.offerId)) {
      this.offerForm.offerId = res.data.offerId
      // }
      this.offerForm.user = res.data.owner
      this.offerForm.operator = res.data.operator
    },
    getWorkrooms() {
      getWorkrooms().then(res => {
        let dept_data = res.data.data
        dept_data.forEach(item => {
          this.deptList.push({value:item.id,label:item.deptName})
        })
      })
    },
    teamChange(){
      this.addOfferForm.optimized='';
      this.addOfferForm.designer='';
    }
  },
  mounted() {

  },

  computed: {
    getLicense() {
      if (this.accountForm.licenseImage != '')
        return [{name: this.accountForm.licenseNo, url: this.accountForm.licenseImage}]
      else
        return []
    },
    getWebsiteImage() {
      if (this.accountForm.websiteScreenshot != '')
        return [{name: this.accountForm.licenseNo,url: this.accountForm.websiteScreenshot}]
      else
        return []
    },
    getAnnex() {
      let annexs=[]
      if (this.accountForm.annexList != []){
        this.accountForm.annexList.forEach((item)=>{
          annexs.push({url:item})
        })
        return annexs;
      }else{
        return []
      }
    },
    filterQueryOptions() {
      return [
        {
          value: 'customerName',
          label: '客户简称',
        },
        {
        value: 'entityName',
        label: '主体名称',
      }, {
        value: 'productName',
        label: '产品名称',
      }, {
        value: 'status',
        label: '开户状态',
        children: this.statusList
      },
        //新增媒体工作室
        {
          value: 'platforms',
          label: '媒体',
          children: this.mediaList
        },{
          value: 'teams',
          label: '团队',
          children: this.deptList
        },
      ]
     },
  },

}

</script>

<style lang="scss" scoped>

.card-header {
  .header-title {
    float: left;
    font-size: 16px;
    font-weight: bold;
  }

  .header-right {
    float: right;
  }
}

::v-deep .el-card__header {
  border-bottom: unset;
}

.curd-table {
  .tab-header {
    font-size: 14px;
    margin-bottom: 15px;

    .tab-header-left {
      float: left;

      & > * {
        margin-right: 15px;
      }
    }

    .tab-header-right {
      float: right;
    }
  }

  .bottom-page {
    margin-top: 25px;
    margin-bottom: 50px;

    .el-pagination {
      float: right;
    }
  }
}

.el-transfer {
  height: 100%;
  display: -webkit-box;

  /deep/ .el-transfer-panel {
    height: 100%;

    .el-transfer-panel__body {
      height: 100%;

      .el-transfer-panel__list {
        height: 100%;
      }
    }
  }
}

.clearfix:after {
  content: "";
  display: block;
  clear: both;
}

.add-form {
  padding: 0 25px;

  .add-title {
    padding: 20px;
    font-size: 16px;
    font-weight: bold;
  }
}

.currencyName{
  height: 32px;
  display: flex;
  align-items: center;
  margin-left: 5px;
}
.setstyle {
  min-height: 200px;
  padding: 0 !important;
  margin: 0;
  overflow: auto;
  cursor: default !important;
}

.el-select, .el-date-editor {
  width: 100%;
}

.cs-button {
  cursor: pointer;
  font-size: 16px;
}

.active {
  color: #409EFF;
}

.disabled {
  cursor: default !important;
}

#message-box {
  display: flex;
  flex-direction: row;
  justify-content: start;
  align-items: start;

  #avatar {
    padding: 5px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    align-items: center;
  }

  #message {
    box-sizing: border-box;
    padding: 10px;
    width: 100%;

    .message-item {
      padding: 5px 15px;
      background-color: #EEE;
      border-radius: 5px;
    }
  }
}

p {
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

//.avatar-uploader .el-upload:hover {
//  border-color: #409EFF;
//}
//
//.avatar-uploader-icon {
//  font-size: 28px;
//  color: #8c939d;
//  width: 178px;
//  height: 178px;
//  line-height: 178px;
//  text-align: center;
//}
//
.avatars {
  /deep/ .avatar-uploader > .el-upload {
    justify-content: center ;
  }
}
//
.addDrawer{
  .el-col{
    margin-bottom: 0px;
  }
  .status{
    font-size: 12px !important;
  }
  .annexDemo{
    width: 100%;
    display: flex;
    flex-wrap: wrap;

  }
  .rightullidiv {
    margin:0px 0px 15px 15px;
    width: 200px;
    height: 200px;
    background: #f2f2f2;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-shrink: 0;
    position:relative;
    .rightulliimg {
      max-width: 200px;
      max-height: 200px;
    }
  }
  .rightullidiv:hover {
    cursor: pointer;
  }
  .rightullidiv:hover::after {
    content: '';
    background-color: rgba(0,0,0,0.5);
    position: absolute;
    left: 0;
    height: 100%;
    top: 0px;
    width: 100%;
    z-index: 99;
    border-radius: 4px;
    align-items: center;
    justify-content: center;
  }
  .rightullidiv i{
    display: none;
  }
  .rightullidiv:hover i {
    position: absolute;
    font-size: 30px;
    display:initial;
    z-index: 999;
    color: #fff;
    top: 40%;
  }
}

</style>


